import elementtree.ElementTree as etree
from duetopia.metadata.base import *
from urllib2 import urlopen

GMD = 'http://www.isotc211.org/2005/gmd'
GTS = 'http://www.isotc211.org/2005/gts'
GCO = 'http://www.isotc211.org/2005/gco'
STR = u'{%s}CharacterString'%GCO
GML = 'http://www.opengis.net/gml'

class ISO19139(Metadata):

    def extract(self,xml=None, uri=None):
        """
        >> md = ISO19139()
        >> o = md.extract(uri='file:samples/iso19139.xml')
        >> o[0].title
        'Physiographic Map of North and Central Eurasia (Sample record, please remove!)'
        >> 
        """
        
        if uri is not None:
            try:
                fp = urlopen(uri)
                xml = fp.read()
                fp.close()
            except:
# @@TODO handle better
                return

        i = etree.fromstring(xml)
        dataset = Dataset()
        dataset.id = i.find(u'{%s}fileIdentifier/%s'%(GMD,STR)).text    

        info = i.find(u'{%s}identificationInfo/{%s}MD_DataIdentification'%(GMD,GMD))
        dataset.title = info.find(u'{%s}citation/{%s}CI_Citation/{%s}title/%s'%(GMD,GMD,GMD,STR)).text
        dataset.abstract = info.find(u'{%s}abstract/%s'%(GMD,STR)).text
        dataset.status = info.find(u'{%s}status/{%s}MD_ProgressCode'%(GMD,GMD)).text

        dataset.language = i.find(u'{%s}language/%s'%(GMD,STR)).text
        dataset.keywords = [] 
        for k in info.findall(u'{%s}descriptiveKeywords/{%s}MD_Keywords/{%s}keyword'):
            dataset.keywords.append(k.find(STR).text)
            # @@ argh, here keywords have languages. the storage model does, this one doesn't. perhaps use a Keyword object here.
        # info/gmd:topicCategory/gmd:MD_TopicCategoryCode
        quality = i.find(u'{%s}dataQualityInfo/{%s}DQ_DataQuality'%(GMD,GMD))    
        dataset.lineage = quality.find(u'{%s}lineage/{%s}LI_Lineage/{%s}statement/%s'%(GMD,GMD,GMD,STR)).text
        
        # what type of data is this? - codelist

        agent = Agent()
        a = i.find(u'{%s}contact/{%s}CI_ResponsibleParty'%(GMD,GMD))
        agent.name = a.find(u'{%s}individualName/%s'%(GMD,STR)).text
        # gmd:organisationName/gco:CharacterString
        # - 2 agents - handling?
        # gmd:positionName/gco:CharacterString
        # - in addition to assigned "role code"
        agent.role = a.find(u'{%s}role/{%s}CI_RoleCode'%(GMD,GMD)).text
        
        datasource = Datasource()
        # @@ need better smaples
        timespan = Timespan()
        dateinfo = info.find(u'{%s}citation/{%s}CI_Citation/{%s}date/{%s}CI_Date/'%(GMD,GMD,GMD,GMD))
        # @@ date range or single date?
        
        point_date = dateinfo.find(u'{%s}date/{%s}DateTime'%(GMD,GCO))
        if point_date is not None:
            # @@ ISO date string formatting -> data storage?
            timespan.date = point_date.text
        else:
            # @@ look for a date range - need samples.
            pass

        # also of interest for I-compliance 
        # gmd:metadataStandardName/gco:CharacterString
        # gmd:metadataStandardVersion/gco:CharacterString
        return dataset, datasource, agent, timespan 
   
    def export(self,file=file):
        pass 
